import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "Home",
      component: () => import("@/views/Home.vue"),
    },
    {
      path: "/login",
      name: "Login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "/todo",
      name: "Todo",
      component: () => import("@/views/Todo.vue"),
      // 登录保护 需要登陆验证才能进入首页
      meta: { requiresAuth: true },
    },
  ],
});

// 登录保护
router.beforeEach((to, from, next) => {
  if (to.name === "Todo" && !localStorage.getItem("userData")) {
    next({ name: "Login" });
    ElMessage.error("请先登录");
  } else {
    next();
  }
});

export default router;
